<!--用户管理页-->
<template>
  <div style="height:6vh;padding:10px 20px;background-color:#fff;">
    <span style="line-height:60px;font-size:20px;">人群管理</span>
    <el-button type="primary"
               style="float: right;margin-top:10px;" @click="beforeAddGroup">+新增人群</el-button>
  </div>
  <!-- 新建用户弹窗 -->
  <el-dialog
      title="dialogTitle"
      style="width: 1000px;padding:40px;"
      v-model="dialogVisible"
  >
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="用户群">
            <el-input placeholder="请输入人群名称" v-model="saveUserForm.groupName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户数量">
            <el-input placeholder="请输入预估用户数量" v-model="saveUserForm.userNumber"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标签集">
            <el-input placeholder="请输入标签集" v-model="saveUserForm.tagIds"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handClose">取消</el-button>
      <el-button type="primary" @click="saveUserGroup">保存</el-button>
    </template>
  </el-dialog>
  <!-- 用户搜索卡片 -->
  <el-card style="margin: 10px;height: 70px;">
    <el-form :inline="true">
      <el-form-item label="用户搜索" style="width: 270px;">
        <el-input placeholder="请输入用户名"
                  v-model="UserGroupFrom.groupName"
                  @keydown.enter="loadGroup"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary"  @click="loadGroup">>查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 用户列表卡片 用户表格数据-->
  <el-card style="margin: 10px;">
    <el-table :data="GroupArr">
      <el-table-column label="编号" type="index" width="80" align="center"></el-table-column>
      <el-table-column label="人群名称" prop="groupName" align="center"></el-table-column>
      <el-table-column label="用户数量" prop="userNumber" align="center"></el-table-column>
      <el-table-column label="创建时间" prop="createAt" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary">编辑</el-button>
          <!-- 确保传递正确的行数据 -->
          <el-button link type="danger" @click="showDeleteDialog(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <el-dialog
          title="删除用户群"
          v-model="deleteDialogVisible"
          width="30%">
        <el-form label-width="100px">
          <el-form-item label="用户群编号">
            <el-input v-model="deleteGroupName" placeholder="请输入要删除的用户群编号"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDelete">确认删除</el-button>
        </template>
      </el-dialog>
    </el-table>
    <el-dialog
        title="删除用户群"
        v-model="deleteDialogVisible"
        width="30%">
      <el-form label-width="100px">
        <el-form-item label="用户群名称">
          <el-input v-model="deleteGroupName" placeholder="请输入要删除的用户群名称"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDelete">确认删除</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import {nextTick, onMounted, ref} from "vue";
import axios from "axios";
import qs from "qs";
import {ElMessage} from "element-plus";
//定义变量控制弹窗是否出现
const dialogVisible = ref(false);

const saveUserForm = ref({
  groupName:'',
  userNumber:'',
  tagIds:'',
});
//定义点击"新建用户"按钮时调用的方法
const beforeAddGroup = ()=>{
  dialogTitle.value = '新建人群';
  dialogVisible.value = true;
}
//定义保存用户的方法
//定义保存用户的方法
const saveUserGroup = () => {
  console.log(saveUserForm.value);
  axios
      .post("http://localhost:8086/v1/usergroup/save", saveUserForm.value, {
        headers: {
          // 设置请求头为 JSON 格式
          "Content-Type": "application/json",
        },
      })
      .then((response) => {
        if (response.data.code === 2000) {
          ElMessage.success("保存成功!");
          // 用户确认关闭后,关闭弹窗
          dialogVisible.value = false;
          //新增成功后,需要重新加载所有的用户数据
          loadGroup();
          // 清空已输入的表单数据
          saveUserForm.value = {
            groupName: "",
            userNumber: "",
          };
        } else {
          ElMessage.error(response.data.msg);
        }
      })
      .catch((error) => {
        console.error("请求出错:", error);
        ElMessage.error("请求失败，请稍后重试");
      });
};
//定义数组用来保存表格数据
const GroupArr = ref([
]);
//定义对象来保存用户查询的条件
const UserGroupFrom = ref({groupName:''});
//定义加载用户列表的方法
const loadGroup = ()=>{
  let data = qs.stringify(UserGroupFrom.value);
  //如果有查询条件,就根据条件查,没有条件默认查全部数据
  axios.get('http://localhost:8086/v1/usergroup/select?'+data)
      .then((response)=>{//回调函数,处理响应数据
        if(response.data.code==2000){//后端返回的状态码是2000说明成功了
          GroupArr.value = response.data.data;//把请求回来的数据装到绑定表格的数组中
          console.log(GroupArr.value);
        }else{
          ElMessage.error(response.data.msg);
        }
      })
}
//定义变量用来保存弹窗的标题
const dialogTitle = ref('新建人群');

//页面一加载完毕,立即执行
onMounted(()=>{
  loadGroup();
})

//重置搜索
const resetSearch = ()=>{
  //清空之前的搜索内容
  UserGroupFrom.value = {};
  //重新加载所有的用户数据
  loadGroup();
}
//定义处理弹窗关闭的方法
const handleClose = ()=>{
  if(confirm('您确认要关闭弹窗吗?')){
    saveUserForm.value = {};
    dialogVisible.value = false;
  }
}
// 控制删除弹窗显示
const deleteDialogVisible = ref(false);
// 保存要删除的用户群编号
const deleteGroupName = ref("");

// 显示删除弹窗
const showDeleteDialog = (row) => {
  console.group('删除弹窗操作开始');
  console.log('点击删除按钮，当前行数据:', row);
  if (!row || !row.id) {
    console.warn('当前行数据缺少 id 字段');
  }
  deleteGroupName.value = row.id || "";
  deleteDialogVisible.value = true;
  console.log('deleteDialogVisible 设为 true，当前值:', deleteDialogVisible.value);

  const observer = new MutationObserver((mutationsList) => {
    for (const mutation of mutationsList) {
      if (mutation.type === 'childList') {
        const dialogElement = document.querySelector('.el-dialog[title="删除用户群"]');
        if (dialogElement) {
          console.log('删除弹窗元素已渲染，样式:', window.getComputedStyle(dialogElement));
          console.log('删除弹窗元素位置:', dialogElement.getBoundingClientRect());
          observer.disconnect();
        }
      }
    }
  });

  observer.observe(document.body, { childList: true, subtree: true });

  console.groupEnd();
};

// 确认删除用户群
const confirmDelete = (groupName) => {
  if (!deleteGroupName.value) {
    ElMessage.warning("请输入要删除的用户群名称");
    return;
  }

  axios.delete(`http://localhost:8086/v1/usergroup/delete/`+groupName)
      .then((response) => {
        if (response.data.code === 2000) {
          ElMessage.success("删除成功!");
          deleteDialogVisible.value = false;
          // 删除成功后，重新加载用户列表
          loadGroup();
        } else {
          ElMessage.error(response.data.msg);
        }
      })
      .catch((error) => {
        console.error("请求出错:", error);
        ElMessage.error("删除失败，请稍后重试");
      });
};

</script>

<style scoped>

</style>